<template>
  <!-- ! 弹框 -->
  <el-dialog
    :title="title"
    :visible.sync="dialogShow"
    width="45%"
    @close="closeDialog"
  >
    <!-- ! 表单 -->
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      label-width="140px"
    >
      <el-form-item label="权限名称" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="权限标识" prop="code">
        <el-input v-model="formData.code"></el-input>
      </el-form-item>
      <el-form-item label="权限描述" prop="description">
        <el-input v-model="formData.description"></el-input>
      </el-form-item>
      <el-form-item label="开启" prop="enVisible">
        <el-switch
          v-model="formData.enVisible"
          active-value="1"
          inactive-value="0"
        >
        </el-switch>
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button size="small" @click="dialogShow = false">取消</el-button>
      <el-button size="small" @click="btnOk" type="primary">确定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { addPermission, updatePermission } from "@/api/permission";

export default {
  name: "addPerm",
  data() {
    return {
      dialogShow: false,
      formData: {
        enVisible: "1",
        name: "",
        code: "",
        description: "",
        type: "",
        pid: "",
      },
      formRules: {
        name: [{ required: true, message: "请输入权限名称", trigger: "blur" }],
        code: [{ required: true, message: "请输入权限标识", trigger: "blur" }],
      },
    };
  },
  computed: {
    title() {
      return this.formData.id ? "修改" : "新增";
    },
  },
  methods: {
    closeDialog() {
      this.$refs.formRef.resetFields();
      this.formData = {
        enVisible: "1",
        name: "",
        code: "",
        description: "",
        type: "",
        pid: "",
      };
    },
    // 表单的提交
    async btnOk() {
      // 1.表单验证
      try {
        await this.$refs.formRef.validate();
      } catch (error) {
        return console.log(error);
      }
      // 2. 整理数据、提交数据
      // 3.提示成功
      if (this.formData.id) {
        await updatePermission(this.formData);
        this.$message.success("修改成功");
      } else {
        await addPermission(this.formData);
        this.$message.success("添加成功");
      }

      //   4. 通知列表更新
      this.$emit("updateList");
      // 5. 关闭弹框
      this.dialogShow = false;
    },
  },
};
</script>
<style lang="scss" scoped></style>
